using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Framework.Library.Core.Utils.Web.UI.Controls
{
    public class CustomCheckBox : CheckBox, IPostBackDataHandler
    {
        public string Value
        {
            get { return (string) ViewState["Value"] ?? string.Empty; }
            set { ViewState["Value"] = value; }
        }

        #region IPostBackDataHandler Members

        bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            string value = postCollection[postDataKey];
            bool isChecked = !string.IsNullOrEmpty(value);
            bool changed = (isChecked != Checked) || (Value != value);

            Checked = isChecked;
            if (value != null)
                Value = value;

            return changed;
        }

        void IPostBackDataHandler.RaisePostDataChangedEvent()
        {
            RaisePostDataChangedEvent();
        }

        #endregion

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);

            writer.AddAttribute(HtmlTextWriterAttribute.Value, Value);
        }
    }
}